package com.health.service;

import com.alibaba.dubbo.config.annotation.Service;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.health.dao.MemberMapper;
import com.health.pojo.Member;
import com.health.vo.PageResult;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.List;
import java.util.Map;

@Service
public class MemberServiceImpl implements MemberService {

    @Resource
    private MemberMapper memberMapper;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int findMemberId(Member member) {
        //根据手机号查询会员id
        Integer memberId = memberMapper.findMemberId(member.getPhoneNumber());
        if (memberId == null) {
            //不存在，则添加到会员表
            memberMapper.add(member);
            //使用新添加的会员id
            memberId = member.getId();
        }
        return memberId;
    }

    @Override
    public Map<String, Object> findMemberReport() {
        return memberMapper.findMemberReport();
    }

    @Override
    public List<Integer> findCountByDate(String firstDay, int[] arr) {
        return memberMapper.findCountByDate(firstDay, arr);
    }

    @Override
    public int update(Member member) {
        return memberMapper.update(member);
    }

    @Override
    public int add(Member member) {
        return memberMapper.add(member);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int deleteById(Integer id) {
        //查看是否在预约表里面，是则不删
        int count = memberMapper.findCountByMemberId(id);
        if (count > 0 ) {
            throw new RuntimeException("该会员有预约，不能删除");
        }
        //没有就直接删除
        return memberMapper.deleteById(id);
    }

    @Override
    public PageResult<Member> findPage(Integer pageNow, Integer pageSize, String query) {

        PageHelper.startPage(pageNow,pageSize);

        //查询
        Page<Member> page= memberMapper.findPage(query);

        return new PageResult<>(page.getTotal(),page.getResult());
    }

    @Override
    public Member findById(Integer id) {
        return memberMapper.findById(id);
    }
}
